package com.iman.locker.persistence;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.iman.dao.AppLocked;
import com.iman.dao.AppLockedDao;
import com.iman.dao.DaoMaster;
import com.iman.dao.DaoSession;
import com.iman.dao.User;
import com.iman.dao.UserDao;
import com.iman.locker.MyApp;
import com.iman.locker.model.AppInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库帮助类
 * Created by esirong on 2015/11/11.
 */
public class DbHelper {

    private static final String TAG = "DbHelper";
    private static DbHelper instance;
    private DaoSession mDaoSession;

    private DbHelper() {
        String DB_Name = "ToucheWise.db";
        initData(DB_Name);
    }

    public static DbHelper getInstance() {
        if (instance == null) {
            instance = new DbHelper();
        }
        return instance;
    }

    /**
     * 初始化数据库
     */
    private void initData(String dataBaseName) {
        Log.d(TAG, "initData");
        Context context = MyApp.getInstance();
        //TODO 初始化数据库
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, dataBaseName, null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster mDaoMaster;
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    /**
     * 获取指定用户
     *
     * @param uid 指定id
     * @return 一个用户信息
     */
    public User getUser(Long uid) {
        UserDao dao = mDaoSession.getUserDao();
        User localUser;
        localUser = dao.loadByRowId(uid);
        return localUser;
    }

    public Long saveUser(User user) {
        UserDao dao = mDaoSession.getUserDao();
        return dao.insertOrReplace(user);
    }

    /**
     * 写入一个被锁APP的信息
     *
     * @param info App信息
     */
    public void add(AppInfo info) {
        AppLockedDao dao = mDaoSession.getAppLockedDao();
        AppLocked applocked = new AppLocked();
        applocked.setLabel(info.label);
        applocked.setPackageName(info.packageName);
        dao.insertOrReplace(applocked);
    }

    /**
     * 删除一个被锁APP的信息（如果存在的话）
     *
     * @param info APP信息
     */
    public void delete(AppInfo info) {
        AppLockedDao dao = mDaoSession.getAppLockedDao();
        dao.deleteByKey(info.packageName);
    }

    /**
     * 查找所有的被锁的APP信息，并返回一个列表
     *
     * @return 被锁APP信息的列表数据
     */
    public List<AppInfo> findAll() {
        AppLockedDao dao = mDaoSession.getAppLockedDao();
        List<AppLocked> list = dao.loadAll();
        List<AppInfo> resultList = new ArrayList<>();
        for (AppLocked appLocked : list) {
            AppInfo info = new AppInfo();
            info.label = appLocked.getLabel();
            info.packageName = appLocked.getPackageName();
            resultList.add(info);
        }
        return resultList;
    }

}
